import { defineStore } from 'pinia'
import { login, register, updateUser } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),
  
  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    // 获取用户角色
    userRole: (state) => state.userInfo.role || ''
  },
  
  actions: {
    // 用户登录
    async loginAction(loginData) {
      try {
        const res = await login(loginData)
        
        if (res.code === 200) {
          const { token, user } = res.data
          
          // 保存token和用户信息
          this.token = token
          this.userInfo = user
          
          // 持久化保存
          localStorage.setItem('token', token)
          localStorage.setItem('userInfo', JSON.stringify(user))
          
          return Promise.resolve(res)
        } else {
          return Promise.reject(res)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 用户注册
    async registerAction(registerData) {
      try {
        const res = await register(registerData)
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 更新用户信息
    async updateUserInfo(userData) {
      try {
        const res = await updateUser(this.userInfo.id, userData)
        
        if (res.code === 200) {
          // 更新本地用户信息
          const updatedUserInfo = {
            ...this.userInfo,
            ...userData
          }
          
          // 删除密码字段，不存储在本地
          if (updatedUserInfo.password) {
            delete updatedUserInfo.password
          }
          
          // 更新状态和本地存储
          this.userInfo = updatedUserInfo
          localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
          
          return Promise.resolve(res)
        } else {
          return Promise.reject(res)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 用户登出
    logout() {
      // 清除状态
      this.token = ''
      this.userInfo = {}
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 返回Promise以便支持异步操作
      return Promise.resolve()
    }
  }
}) 